package com.hxc.pay.wx.utils;

import com.alibaba.fastjson.JSON;
import com.hxc.pay.wx.config.WxPayProperties;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class SignUtils {
    //私钥
//    private String privateKey="-----BEGIN PRIVATE KEY-----\n" +
//            "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQChXKhMDNcjxTBO\n" +
//            "FF2NOHai5NwChO12f3KQbmqCNEXWImqC5OtTEmcy/8Kzx8i243TtkVFv+Eqvac69\n" +
//            "/gpytl8sK8GFCzzUExgtejrtr3cJS//0eaJURGVG9zDPHrGV5vtXqmUPzAzX5SbM\n" +
//            "sIEKAZoe2bRJRz5zNNx+RMReSOC7F4xn+5tQd3XmZomwFGKO0oryKEocw5IGdYL6\n" +
//            "1zRkUK9yRtyDZKq7hvPv11YQgnD8+EeGgo5/0kk62sbWW545Hw1qVqkQjkOfbdtL\n" +
//            "Qjz4BnbakUwdRn3qoCjga8QQp0EKaGbIu4haHReyP8QQZhq0KlRX6XjBbrk8k4yK\n" +
//            "URVkjrxVAgMBAAECggEAT7HjrSvqVdBeOzHzwnvQnENMJjJg1dW8T3k5QXVvyILW\n" +
//            "+C73yt+b+KQ5FXHmv+03It5Sympm+JvZcBy4LE/GUZqKyZrzQAruNgfYcuvmbsEK\n" +
//            "eURZ2CSvoI0VnjYan16lZHbT0ymEblzO/Olv0fFYnUQItuho/51sCTENi0OTOtNt\n" +
//            "rWahbOnrBk+WsgmhNen+W/KdFXA9EOFKoFclAPEpCUa/mi1/w7AQecHZUISeRXix\n" +
//            "SZbhHIF4bf7BDXqkgtnWEkBX2hZP61TibGiRUgHvVC6V5+bi07cv7jr6IjJdNvwK\n" +
//            "MjAw2GgwZvyb8HvcQ0M7ULmYC6ZXYfVuvZDXJuMCAQKBgQDTAltDJ3oE1tJtk3qg\n" +
//            "ichuWf8OKlvNmN2fxiDG+rxOgTi2gL9N3BKIYWQRo3f2B9C243Z1iM+Q/4LPii6F\n" +
//            "iLTSPQYRcNaryB1BtNGjexHMK5NuCfZ2etx3zmYz86YiWY6ZsFuISFttdPq01MKR\n" +
//            "xN/gIfiXvRlv4g1SIK6vy3lpjQKBgQDDxF/Q2xNFZq8WZ4M1DW3r9EcnYgn6U8qK\n" +
//            "fDJFvW4VT9bHOJOxxmZ3oIccSuPky7gm9DlxRC632z1FyPu6buC7pp7X8+JJPmkq\n" +
//            "2c0fKYl5B5boJdBCs8QrRQ89oORFuB3/2on9N6YCMccf1VQ3kspm5GhEkO/mdN7u\n" +
//            "NYBRq1oX6QKBgAT77UPszskGefn0ndTk7EMPBSNEhN6aWcHIYEXS7le8XaaR6/Le\n" +
//            "2+E0y7RO9CpvjNKFFOs5zA1Uu7ZDQU4OKJc+scH/tFJia659ouYFpin4bYcP3S53\n" +
//            "QHXj/i4D90ygaOngbIkPjHlNZg6XZ/EhgVg99S1AXjVyVXY3J2knmTqRAoGAfuht\n" +
//            "yOJMMuBnPpnqB9ll2eFowxIeL8Zj9bSfjnBHzc8NB+cYb9WTFZfeHqw54ldiUPZf\n" +
//            "ypqNwqiApx2semZoj51rOcmjdyHbYWkCPWJa+Te/T008HhGVaQuC3svPT5cU84jD\n" +
//            "jYCmwKNuV6eeycwCJAOLyG9A5d/7qObMAaWYaQkCgYBge3oRaGlDujnn0UDwLppi\n" +
//            "ytsr4TDuDvkaRLCx4OrT86Yr+gWGjo46pBYIPJ8yy59yRTVYTpDiOLLC51qweh2w\n" +
//            "Ko6+/qtzNwp41jadphbpEgGRE+mpvUWtlj4yPkojSY83Gh36eWVGISDG95z1DDjj\n" +
//            "sGT8hwQgcQJHrQhWn/cltQ==\n" +
//            "-----END PRIVATE KEY-----";

    private WxPayProperties wxPayProperties;

    public SignUtils(WxPayProperties wxPayProperties) {
        this.wxPayProperties = wxPayProperties;
    }

    public String sign(byte[] message) throws Exception {

        Signature sign = Signature.getInstance("SHA256withRSA");
//        PrivateKey merchantPrivateKey = PemUtil
//                .loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));
        PrivateKey merchantPrivateKey = PemUtil
                .loadPrivateKey(new FileInputStream(new File(wxPayProperties.getPrivateKeyFilePath())));
        sign.initSign(merchantPrivateKey);

        sign.update(message);

        return Base64.getEncoder().encodeToString(sign.sign());
    }

   public String buildMessage(String appId, long timestamp, String nonceStr, String packageStr) {
        return appId + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + packageStr + "\n";
    }




    /**
     *
     * @param packageStr  prepay_id=xxxxxxxxx
     *
     * @return  json字符串
     *  {
     *      nonceStr:"",
     *      paySign:
     *      timeStamp:
     *      signType:
     *      packageStr:
     *
     *  }
     */
   public String sign(String packageStr){

       long timestemp = System.currentTimeMillis();
       String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
       String message = buildMessage(wxPayProperties.getAppid(), timestemp, nonceStr, packageStr);
       String sign = null;
       try {
           sign = sign(message.getBytes(StandardCharsets.UTF_8));
       } catch (Exception e) {
           e.printStackTrace();
       }

       Map<String,Object> map = new HashMap<>();
       map.put("nonceStr",nonceStr);
       map.put("paySign",sign);
       map.put("signType","RSA");
       map.put("packageStr",packageStr);
       map.put("timeStamp",timestemp);


       return JSON.toJSONString(map);
    }
}
